from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin
from admin.utils.page import Mypage
from system.serializer.dept import DeptSerializer, CreateDeptSerializer, UpdateDeptSerializer, DeptSuperiorSerializer
from rest_framework.filters import SearchFilter
from system.models import Dept
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView


class DeptAllView(GenericViewSet, ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = Dept.objects.filter(is_delete=False).order_by('id')
    serializer_class = DeptSerializer
    filter_backends = [SearchFilter, ]
    search_fields = ['name']
    pagination_class = Mypage

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        pid = request.GET.get('pid')
        if not pid and not request.GET.get('name'):
            queryset = queryset.filter(pid=None)
        elif request.GET.get('name'):
            queryset = queryset
        else:
            queryset = queryset.filter(pid=pid)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_del_object(request)
        for i in instance:
            self.perform_destroy(i)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.update(is_delete=True)

    def get_del_object(self, request):  # 单个删除或批量删除
        id_list = request.data
        Dept_list = []
        for id in id_list:
            Dept_list.append(Dept.objects.filter(pk=id))
        return Dept_list

    def get_object(self, request):
        pk = request.data.get('id')
        return Dept.objects.filter(pk=pk).first()

    def get_serializer_class(self):
        if self.action == 'list':
            return DeptSerializer
        elif self.action == 'create':
            return CreateDeptSerializer
        elif self.action == 'update':
            return UpdateDeptSerializer


class DeptSuperiorView(APIView):
    def post(self, request):
        """
        拿到当前修改的部门id返回他的父部门信息和父部门的所有子部门信息
        优化:
            直接返回所有的顶级部门
            如果有请求的部门列表则在返回父部门的列表的同时带着请求部门过去
        :param request:
        :return:
        """
        dept = Dept.objects.filter(pk=request.data[0]).first()  # 当前修改部门
        parent_id = dept.pid.pk if dept.pid else dept.pid  # 父部门的id   4
        update_dept_list = []
        if parent_id:
            update_dept_list.append(dept.pid)
            for i in Dept.objects.filter(pid_id=parent_id, is_delete=False):  # 和当前修改部门同一级的部门
                update_dept_list.append(i)
        else:  # 当前修改部门是顶级部门
            for i in Dept.objects.filter(pid=None, is_delete=False):
                update_dept_list.append(i)
        results = []
        for dept in update_dept_list:
            results.append({
                'createBy': dept.create_by,
                'createTime': dept.create_time,
                'deptSort': dept.dept_sort,
                'enabled': dept.enabled,
                'hasChildren': True if dept.sub_count > 0 else False,
                'id': dept.id,
                'label': dept.name,
                'leaf': True if dept.sub_count < 0 else False,
                'name': dept.name,
                'subCount': dept.sub_count,
                'updateBy': dept.update_by,
                'updateTime': dept.update_time
            })
        data = {
            'results': results,
            'count': len(results)
        }
        # dept_list = Dept.objects.filter(is_delete=False, pid_id=None)
        # request_list = request.data
        # children = []
        # for i in request_list:
        #     for dept in Dept.objects.filter(pk = i):
        #         children.append({
        #             'createBy': dept.create_by,
        #             'createTime': dept.create_time,
        #             'deptSort': dept.dept_sort,
        #             'enabled': dept.enabled,
        #             'hasChildren': True if dept.sub_count > 0 else False,
        #             'id': dept.id,
        #             'label': dept.name,
        #             'leaf': True if dept.sub_count < 0 else False,
        #             'name': dept.name,
        #             'subCount': dept.sub_count,
        #             'updateBy': dept.update_by,
        #             'updateTime': dept.update_time,
        #         })
        # results = []
        # for dept in list(dept_list):
        #     results.append({
        #             'createBy': dept.create_by,
        #             'createTime': dept.create_time,
        #             'deptSort': dept.dept_sort,
        #             'enabled': dept.enabled,
        #             'hasChildren': True if dept.sub_count > 0 else False,
        #             'id': dept.id,
        #             'label': dept.name,
        #             'leaf': True if dept.sub_count < 0 else False,
        #             'name': dept.name,
        #             'subCount': dept.sub_count,
        #             'updateBy': dept.update_by,
        #             'updateTime': dept.update_time,
        #         })
        # results[0]['children'] = children
        # data = {
        #     'results': results,
        #     'count': len(results)
        # }
        return Response(data)


# class DeptSuperiorView(GenericAPIView, CreateModelMixin):
#     serializer_class = DeptSuperiorSerializer
#     queryset = Dept.objects.filter(is_delete=False)
#
#     def post(self, request, *args, **kwargs):
#         """
#         根据ID获取同级与上级数据
#         :param request:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         request_id = request.data.get('id')[0]
#         parent_dept = Dept.objects.filter(pid_id=request_id).first()        # 获取父级部门
#         same_level_dept = Dept.objects.filter(pid = parent_dept)            # 所有的同级部门
#
